package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;

/**购物车
 * @author Administrator
 *
 */
public class Shop3 extends Activity {

	private List[] list_gwcs;
	private List<Map<String, Object>> list_gwc;
	private ListView lv_gwc;
	private Button btn_buy; // 提交订单
	private TextView  tv_je;
	MyApplication app;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.shop3_main);
		MyApplication myApplication;
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		findView();

		getData();

		setListener();
	}

	private void findView() {

		lv_gwc = (ListView) this.findViewById(R.id.listView);

		app = (MyApplication) this.getApplication();
		list_gwcs = app.getList_gwc();

		list_gwc = new ArrayList<Map<String, Object>>();
		tv_je = (TextView) this.findViewById(R.id.tv_je);
		btn_buy = (Button)this.findViewById(R.id.btn_buy);

	}

	private void setListener() {
		btn_buy.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String s1 = tv_je.getText().toString().trim().split("¥")[1];
				if (s1.equals("")||(Double.valueOf(s1)==0.0)) {
					Toast.makeText(Shop3.this, "商品数量不能都为空！",
							Toast.LENGTH_SHORT).show();
					return;
				}
				Map<String, Object> spmap = new HashMap<String, Object>();
				String spmx = "";
				String imgpath = "";
				for (int i = 0; i < list_gwc.size(); i++) {
					spmap = list_gwc.get(i);
					if(Integer.valueOf(spmap.get("num").toString())>0){
						imgpath =spmap.get("imgpath")==null?"":spmap.get("imgpath").toString();
						spmx += "#"+spmap.get("name").toString()+"@"+
								spmap.get("price").toString()+"@"+
								spmap.get("dw").toString()+"@"+
								imgpath+"@"+
								spmap.get("lbid").toString()+"@"+
								spmap.get("spid").toString()+"@"+
								spmap.get("num").toString();
					}
				}
				
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("spmx", spmx));
				params.add(new BasicNameValuePair("je", s1));
				params.add(new BasicNameValuePair("drzh", app.getAccount()));

				JSONObject res = HTTPGetTool.getTool().post(
						URLUtils.HOST + URLUtils.SPDDXXSAVE, params);
				String saveInfo = "SAVE_NOTSUCCESS";
				if (res != null) {
					try {
						saveInfo = res.get("spInfo").toString();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Toast.makeText(Shop3.this,
								"下单失败(原因：" + e.toString() + ")",
								Toast.LENGTH_SHORT).show();
					}
				}

				if (saveInfo.equals("SAVE_SUCCESS")) {
					Toast.makeText(Shop3.this, "下单成功,选择继续购物", Toast.LENGTH_SHORT)
							.show();
					// 到下一页面
					Shop.instance.finish();
					Intent intent = new Intent();
					intent.setClass(Shop3.this, Shop.class);
					Shop3.this.startActivity(intent);
					
					finish();
				} else if (saveInfo.equals("SAVE_NOTSUCCESS")) {
					Toast.makeText(Shop3.this, "下单失败", Toast.LENGTH_SHORT)
							.show();
				}

			}
		});
	}

	private void getData() {
		new Thread(new LoadData()).start();

	}

	class LoadData implements Runnable {

		public void run() {
			// TODO Auto-generated method stub
			Looper.prepare();
			iniData();
			Looper.loop();
		}
	}

	private void iniData() {
		Message msg = mUIHandler.obtainMessage();
		Bundle bundle = new Bundle();

		List<Map<String, Object>> list_temp = null;
		if (list_gwcs.length > 0) {
			for (int i = 0; i < list_gwcs.length; i++) {
				list_temp = list_gwcs[i];
				if (list_temp != null && list_temp.size() > 0) {
					for (int j = 0; j < list_temp.size(); j++) {
						list_gwc.add(list_temp.get(j));
					}
				}

			}
		}
		bundle.putInt("type", 0);
		bundle.putString("msg", "");
		msg.setData(bundle);
		mUIHandler.sendMessage(msg);
	}

	private Handler mUIHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			int type = msg.getData().getInt("type");
			switch (type) {
			case -1:
				// proDialog.dismiss();
				Toast.makeText(Shop3.this, msg.getData().getString("msg"),
						Toast.LENGTH_SHORT).show();
				break;
			case 0: {
				setData();
				break;
			}

			}

		}

	};

	private void setData() {
		MyAdapter myAdapter = new MyAdapter(this);
		if (list_gwc != null) {
			myAdapter.setList(list_gwc);

			lv_gwc.setAdapter(myAdapter);
			
			Map<String, Object> newmap = new HashMap<String, Object>();
			double je = 0.0;
			for (int i = 0; i < list_gwc.size(); i++) {
				newmap = list_gwc.get(i);
				je += Double.valueOf(newmap.get("price").toString())*Integer.valueOf(newmap.get("num").toString());
				
			}
			tv_je.setText("¥"+je+"");
		}

	}

	private class MyAdapter extends BaseAdapter {
		private List<Map<String, Object>> list;
		private LayoutInflater mLayoutInflater;

		public List<Map<String, Object>> getList() {
			return list;
		}

		public void setList(List<Map<String, Object>> list) {
			this.list = list;
		}

		public MyAdapter(Context context) {
			mLayoutInflater = (LayoutInflater) context
					.getSystemService(LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mLayoutInflater.inflate(R.layout.shop3_sub, null);
				holder = new ViewHolder();
				holder.gridview_imageview = (ImageView) convertView
						.findViewById(R.id.iv_img);
				holder.tv_name = (TextView) convertView
						.findViewById(R.id.tv_name);
				holder.tv_price = (TextView) convertView
						.findViewById(R.id.tv_price);
				holder.tv_dw = (TextView) convertView
						.findViewById(R.id.tv_dw);
				holder.tv_num = (TextView) convertView
						.findViewById(R.id.tv_num);
				holder.tv_sl = (TextView) convertView.findViewById(R.id.tv_sl);
				holder.btn_add = (ImageView) convertView
						.findViewById(R.id.btn_add);
				holder.btn_minus = (ImageView) convertView
						.findViewById(R.id.btn_minus);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.gridview_imageview.setImageBitmap((Bitmap) list
					.get(position).get("pic"));
			holder.tv_name.setText(list.get(position).get("name").toString());
			holder.tv_price.setText(list.get(position).get("price").toString());
			holder.tv_dw.setText(list.get(position).get("dw").toString());
			holder.tv_num.setText(list.get(position).get("num").toString());
			holder.tv_sl.setText(list.get(position).get("num").toString());
			final int position_new = position;
			final TextView tv_sl = holder.tv_sl;

			holder.btn_minus.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					String sl = tv_sl.getText().toString();
					int sl_ = Integer.parseInt(sl) - 1;
					if(sl_<0){
						sl_=0;
					}
					tv_sl.setText(sl_ + "");
					list.get(position_new).put("num", sl_);
					Map<String, Object> newmap = new HashMap<String, Object>();
					double je = 0.0;
					for (int i = 0; i < list.size(); i++) {
						newmap = list.get(i);
						je += Double.valueOf(newmap.get("price").toString())*Integer.valueOf(newmap.get("num").toString());
						
					}
					tv_je.setText("¥"+je+"");
				}
			});

			holder.btn_add.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					String sl = tv_sl.getText().toString();
					int sl_ = Integer.parseInt(sl) + 1;
					tv_sl.setText(sl_ + "");
					
					list.get(position_new).put("num", sl_);
					Map<String, Object> newmap = new HashMap<String, Object>();
					double je = 0.0;
					for (int i = 0; i < list.size(); i++) {
						newmap = list.get(i);
						je += Double.valueOf(newmap.get("price").toString())*Integer.valueOf(newmap.get("num").toString());
						
					}
					tv_je.setText("¥"+je+"");
				}
			});

			return convertView;
		}
	}

	public class ViewHolder {
		private ImageView gridview_imageview;
		private TextView tv_name;
		private TextView tv_price;
		private TextView tv_dw;
		private TextView tv_num;
		private ImageView btn_minus;
		private ImageView btn_add;
		private TextView tv_sl;
	}

}
